package com.lsl.myfilemanager.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;
;import com.lsl.myfilemanager.R;
import com.lsl.myfilemanager.util.FormatTime;

/**
 * author lishilin
 * date 2023-7-25
 * 描述 视频播放器，自定义播放进度条
 */

public class VideoActivity extends Activity implements View.OnClickListener {
    private VideoView video;
    private TextView startPlay;
    private TextView pausePlay;
    private ImageButton closeBtn;
    private int totalSeconds;//视频总时长，单位，毫秒
    private int currentSeconds;//当前视频进度
    private int seekBarMax;//进度条最大值
    private SeekBar seekBar;//进度条
    private TextView seekBarMaxSecond;//进度条最大秒数
    private TextView seekBarStartSecond;//进度条开始秒数
    private FormatTime formatTime;
    private TextView replay;
    private TextView videoTitle;
    private boolean playFlag = false;

    @Override
    public void onCreate(Bundle saveInstanceState) {
        super.onCreate(saveInstanceState);
        setContentView(R.layout.video_play);
        Intent intent = getIntent();
        String videoPath = intent.getStringExtra("path");
        String videoName = intent.getStringExtra("name");
        initView(videoPath, videoName);
        formatTime = new FormatTime();
        updateSeekbar();//监听进度条滑块
        playListener();//设置视频加载监听器
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//强制页面横屏
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.play_video:
                if (!video.isPlaying()) {
                    video.start();
                }
                break;
            case R.id.pause_video:
                if (video.isPlaying()) {
                    video.pause();
                }
                break;
            case R.id.replay_video:
                video.resume();
                break;
            case R.id.closeVideo:
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 初始化组件
     */
    private void initView(String path, String name) {
        video = (VideoView) findViewById(R.id.video);
        video.setVideoPath(path);
        video.requestFocus();//视频获取焦点
        seekBar = (SeekBar) findViewById(R.id.seekbar_video);
        seekBarMaxSecond = (TextView) findViewById(R.id.seekbar_max_second);
        seekBarStartSecond = (TextView) findViewById(R.id.seekbar_start_second);
        closeBtn = findViewById(R.id.closeVideo);

        replay = (TextView) findViewById(R.id.replay_video);
        replay.setOnClickListener(this);
        startPlay = (TextView) findViewById(R.id.play_video);
        pausePlay = findViewById(R.id.pause_video);
        videoTitle = findViewById(R.id.videoTitle);
        videoTitle.setText(name);
        startPlay.setOnClickListener(this);
        pausePlay.setOnClickListener(this);
        closeBtn.setOnClickListener(this);
    }

    /**
     * 设置视频播放时候的动作监听，并作出相应的处理，比如进度条更新等操作
     */
    private void playListener() {
        //监听视频准备加载完毕之后执行
        video.setOnPreparedListener(mediaPlayer -> {
            video.start();
            playFlag = true;
            totalSeconds = video.getDuration();//获取视频总毫秒数
            seekBarMaxSecond.setText(formatTime.SecondToTime(totalSeconds / 1000));//设置进度条最大时间秒数
            seekBarMax = totalSeconds;
            seekBar.setMax(seekBarMax);
            //异步更新ui，利用消息机制处理子线程的需求
            @SuppressLint("HandlerLeak") Handler mhandler = new Handler() {
                @Override
                public void handleMessage(Message message) {
                    if (message.what == 1) {
                        updateProcess();//更新视频播放时间和进度条
                    }
                }
            };
            //子线程里执行循环发送消息
            new Thread(new Runnable() {
                @Override
                public void run() {
                    currentSeconds = video.getCurrentPosition();//获取视频播放进度，返回值为毫秒
                    while (playFlag) {
                        Message message = new Message();
                        message.what = 1;
                        mhandler.sendMessage(message);
                        try {
                            Thread.sleep(100);//设置一毫秒更新一次进度条ui，这里可以改成想要的值
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        });
    }

    /**
     * 更新视频播放时间和进度条
     */
    private void updateProcess() {
        currentSeconds = video.getCurrentPosition();
        seekBarStartSecond.setText(formatTime.SecondToTime(currentSeconds / 1000));
        seekBar.setProgress(currentSeconds);
    }

    /**
     * 监听进度条滑块
     */
    public void updateSeekbar() {
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            //停止滑动的时候执行下面的方法
            @Override
            public void onStopTrackingTouch(SeekBar seekBar1) {
                int current = seekBar.getProgress();
                video.seekTo(current);
                seekBarStartSecond.setText(formatTime.SecondToTime(currentSeconds / 1000));
            }
        });
    }

    @Override
    public void onDestroy() {
        playFlag = false;
        video.suspend();
        Log.i("视频播放器", "释放资源");
        super.onDestroy();
    }
}
